const  newsService  = require('../../services/admin/newsService');

const JWT = require('../../utils/JWT')

const newsController = {
    // 添加新闻逻辑
    add: async(req, res , next) => {

        const { title, content, category,isPublish } = req.body
        const cover = req.file ? `newsUploads/${req.file.filename}` : ''
        // 调用服务层添加新闻
        await newsService.add({
            title,
            content, 
            category: Number(category),
            cover,
            isPublish: Number(isPublish),
            updateTime: new Date()
        });

        res.send({
            ActionType: "OK",
            status: 200,
            cover 
        })
    },
    // 获取新闻列表
    list: async(req, res , next) => {
        const result = await newsService.list()

        res.send({
            ActionType: "OK",
            status: 200,
            data: result
        })
    },
    // 切换发布状态
    publish: async (req, res, next) => {
        const { _id, isPublish } = req.body
        await newsService.publish({ _id, isPublish, updateTime: new Date()});
        res.send({
            ActionType: "OK",
            status: 200,
            message: '切换发布状态成功',
            isPublish
        })
    },
    // 删除新闻
    delete: async (req, res, next) => {
        const id  = req.query.id
        await newsService.delete(id);

        res.send({
            ActionType: "OK",
            status: 200,
            message: '删除成功',
            id
        })
    },
    // 获取新闻详情
    detail: async (req, res, next) => {
        const id  = req.query.id
        const result = await newsService.detail(id);

        res.send({
            ActionType: "OK",
            status: 200,
            data: result
        })
    },
    // 更新新闻
    update: async (req, res, next) => {
        const { _id, title, content, isPublish, category} = req.body
        let  cover = ''
        // 处理图片上传
        if (req.file) {
             cover = `newsUploads/${req.file.filename}`
        } else {
            cover = req.body.cover.split('3000/')[1]// 去掉http://localhost:3000/前缀，只保留相对路径部分，避免上传文件时出现重复文件名导致覆盖
        }

        await newsService.update({
            _id,
            title,
            content,
            isPublish,
            cover,
            category,
            updateTime: new Date() // 更新新闻时，将创建时间设置为当前时间
        });


        res.send({
            ActionType: "OK",
            status: 200,
            message: '更新成功',
            cover
        })
    }
}

module.exports = newsController;